package cn.school.web.controller.client;

import cn.school.common.config.RuoYiConfig;
import cn.school.common.constant.enums.DataStatusEnum;
import cn.school.common.core.domain.AjaxResult;
import cn.school.common.utils.file.FileUploadUtils;
import cn.school.system.domain.*;
import cn.school.system.model.req.CreateOrderDTO;
import cn.school.system.model.resp.CreateOrderRespDTO;
import cn.school.system.model.resp.UserPaperExtractListRespDTO;
import cn.school.system.service.*;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static cn.school.common.core.domain.AjaxResult.error;
import static cn.school.common.core.domain.AjaxResult.success;

/**
 * @author zsj
 * @version 1.0
 * @date 2023/12/15 21:42
 * @desc
 **/
@RestController
@RequestMapping("/h5/client")
public class H5ClientController {
    @Autowired
    private IBiGoodService biGoodService;
    @Autowired
    private IBiSchoolService biSchoolService;
    @Autowired
    private IBiPaperService biPaperService;
    @Autowired
    private IBiOrderInfoService biOrderInfoService;
    @Autowired
    private IBiExtractPaperService biExtractPaperService;
    @Autowired
    private IBiShopService biShopService;
    @Autowired
    private IBiBankAccountService biBankAccountService;
    @Autowired
    private IBiCashApplyService cashApplyService;
    @Autowired
    private IBiCommissionService commissionService;

    @GetMapping("/good/list")
    public AjaxResult goodList(){
        BiGood tempGood = new BiGood();
        tempGood.setStatus(DataStatusEnum.USABLE.getStatus());
        return success(biGoodService.selectBiGoodList(tempGood));
    }

    @GetMapping("/school/list")
    public AjaxResult schoolList(BiSchool school){
        school.setStatus(DataStatusEnum.USABLE.getStatus());
        return success(biSchoolService.selectBiSchoolList(school));
    }

    @PostMapping("/order/save")
    public AjaxResult orderSave(@RequestBody CreateOrderDTO dto) {
        try {
            if(dto.getPaper()!=null){
                String errMsg = this.validNull(dto.getPaper());
                if(StringUtils.isNotEmpty(errMsg)){
                    return error(errMsg);
                }
            }
            CreateOrderRespDTO respDTO = biOrderInfoService.save(dto);
            if(respDTO.getSaveSuccessFlag()) {
                return success(respDTO);
            }else{
                return error(respDTO.getSaveFailMsg());
            }
        }catch (Exception e){
            e.printStackTrace();
            return error("失败，请重试，"+e.getMessage());
        }
    }

    private String validNull(BiPaper paper) {
        String errMsg = null;
        if(paper.getSchoolId()==null){
            errMsg = "请选择学校信息";
            return errMsg;
        }

        boolean flag = false;
        if(StringUtils.isNotEmpty(paper.getQqNumber())){
            flag = true;
        }
        if(StringUtils.isNotEmpty(paper.getWxNumber())){
            flag = true;
        }
        if(StringUtils.isNotEmpty(paper.getWxQrcode())){
            flag = true;
        }
        if(StringUtils.isNotEmpty(paper.getNote())){
            flag = true;
        }
        if(!flag){
            errMsg = "请填写纸条信息";
        }
        return errMsg;
    }

    @GetMapping("/paper/countByOpenid")
    public AjaxResult countPaperByOpenid(BiPaper paper){
        if(StringUtils.isNotEmpty(paper.getOpenid())) {
            return success(biPaperService.findByOpneidCount(paper.getOpenid()));
        }else {
            return success(10);
        }
    }

    //查询放入的列表
    @GetMapping("/userPaper/increase/list")
    public AjaxResult userPaperIncreaseList(BiPaper paper){
        if(StringUtils.isNotEmpty(paper.getOpenid())) {
            paper.setStatus(0);
            return success(biPaperService.selectBiPaperList(paper));
        }else {
            return success(new ArrayList<>());
        }

    }

    //查询抽取的列表
    @GetMapping("/userPaper/extract/list")
    public AjaxResult userPaperExtractList(BiPaper paper) throws Exception {
        if(StringUtils.isNotEmpty(paper.getOpenid())) {
            BiExtractPaper temp = new BiExtractPaper();
            temp.setOpenid(temp.getOpenid());
            List<UserPaperExtractListRespDTO> list = biExtractPaperService.selectBiExtractPaperListByOpenid(paper.getOpenid());
            for (UserPaperExtractListRespDTO dto: list) {
                if(StringUtils.isNotBlank(dto.getWxQrcode())){
                    dto.setWxQrcode(URLEncoder.encode(dto.getWxQrcode(),"utf-8"));
                }
            }
            return success(list);
        }else {
            return success(new ArrayList<>());
        }

    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(file);
            String url = fileName;

            JSONObject json = new JSONObject();
            json.put("url", url);

            return success(json);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    //销毁纸条
    @PostMapping("/userPaper/increase/delete")
    public AjaxResult userPaperIncreaseDelete(@RequestBody BiPaper paper){
        if(StringUtils.isNotEmpty(paper.getOpenid()) && paper.getId()!=null && paper.getId().intValue()>0) {
            BiPaper check = biPaperService.selectBiPaperById(paper.getId());
            if(StringUtils.isNotBlank(check.getOpenid()) && check.getOpenid().equals(paper.getOpenid())) {
                BiPaper updateTemp = new BiPaper();
                updateTemp.setId(paper.getId());
                updateTemp.setStatus(DataStatusEnum.DELETE.getStatus());
                return success(biPaperService.updateBiPaper(updateTemp));
            }else{
                return error("删除失败，无权限");
            }
        }else {
            return error("删除失败，参数错误");
        }
    }

    //删除抽取记录
    @PostMapping("/userPaper/extract/delete")
    public AjaxResult userPaperExtractDelete(@RequestBody BiExtractPaper extractPaper){
        if(StringUtils.isNotEmpty(extractPaper.getOpenid()) && extractPaper.getId()!=null && extractPaper.getId().intValue()>0) {
            UserPaperExtractListRespDTO check = biExtractPaperService.selectBiExtractPaperById(extractPaper.getId());
            if(StringUtils.isNotBlank(check.getOpenid()) && check.getOpenid().equals(extractPaper.getOpenid())) {
                BiExtractPaper updateTemp = new BiExtractPaper();
                updateTemp.setId(extractPaper.getId());
                updateTemp.setStatus(DataStatusEnum.DELETE.getStatus());
                return success(biExtractPaperService.updateBiExtractPaper(updateTemp));
            }else{
                return error("删除失败，无权限");
            }
        }else {
            return error("删除失败，参数错误");
        }
    }

    //更新状态
    @PostMapping("/userPaper/extract/updateStatus")
    public AjaxResult userPaperExtractUpdateStatus(@RequestBody BiExtractPaper extractPaper){
        if(StringUtils.isNotEmpty(extractPaper.getOpenid()) && extractPaper.getId()!=null && extractPaper.getId().intValue()>0) {
            UserPaperExtractListRespDTO check = biExtractPaperService.selectBiExtractPaperById(extractPaper.getId());
            if(StringUtils.isNotBlank(check.getOpenid()) && check.getOpenid().equals(extractPaper.getOpenid())) {
                BiExtractPaper updateTemp = new BiExtractPaper();
                updateTemp.setId(extractPaper.getId());
                updateTemp.setStatus(extractPaper.getStatus());
                return success(biExtractPaperService.updateBiExtractPaper(updateTemp));
            }else{
                return error("删除失败，无权限");
            }
        }else {
            return error("删除失败，参数错误");
        }
    }

    //重新抽取纸条
    @PostMapping("/userPaper/extract/reset")
    public AjaxResult userPaperExtractReset(@RequestBody BiExtractPaper extractPaper){
        if(StringUtils.isNotEmpty(extractPaper.getOpenid()) && extractPaper.getId()!=null && extractPaper.getId().intValue()>0) {
            UserPaperExtractListRespDTO check = biExtractPaperService.selectBiExtractPaperById(extractPaper.getId());
            if(StringUtils.isNotBlank(check.getOpenid()) && check.getOpenid().equals(extractPaper.getOpenid())) {
                BiPaper paper = biPaperService.selectBiPaperById(extractPaper.getPaperId());
                if(paper==null){
                    return error("重新抽取失败，未找到源数据");
                }

                //抽取纸条
                List<Long> list = biPaperService.extractPaper(extractPaper.getOpenid(),null, paper.getSchoolId(), check.getPaperId());
                if(list!=null && list.size()>0){
                    BiExtractPaper updateTemp = new BiExtractPaper();
                    updateTemp.setId(extractPaper.getId());
                    updateTemp.setStatus(DataStatusEnum.USABLE.getStatus());
                    updateTemp.setPaperId(list.get(0));
                    biExtractPaperService.updateBiExtractPaper(updateTemp);

                    UserPaperExtractListRespDTO newPaper = biExtractPaperService.selectBiExtractPaperById(extractPaper.getId());

                    return success(newPaper);
                }else{
                    return error("重新抽取失败，请重试");
                }
            }else{
                return error("重新抽取失败，无权限");
            }
        }else {
            return error("重新抽取失败，参数错误");
        }
    }

    //查询店铺信息
    @GetMapping("/shop/getShopByOpenid")
    public AjaxResult getShopByOpenid(BiShop biShop){
        if(StringUtils.isNotBlank(biShop.getOpenid())) {
            BiShop shop = biShopService.selectBiShopByOpenid(biShop.getOpenid());
            if(shop!=null){
                shop.setPassword("这不是密码");
            }
            return AjaxResult.success(shop);
        }else{
            return AjaxResult.success();
        }
    }

    //查询银行账号信息
    @GetMapping("/shop/bankAccount/list")
    public AjaxResult bankAccountList(BiBankAccount bankAccount){
        if(StringUtils.isNotBlank(bankAccount.getOpenid())) {
            List<BiBankAccount> bankList= biBankAccountService.selectBiBankAccountList(bankAccount);
            return AjaxResult.success(bankList);
        }else{
            return AjaxResult.success();
        }
    }

    //查询银行账号信息
    @PostMapping("/shop/bankAccount/add")
    public AjaxResult addBankAccount(@RequestBody BiBankAccount bankAccount){
        if(StringUtils.isNotBlank(bankAccount.getOpenid())
                && StringUtils.isNotBlank(bankAccount.getBankName())
                && StringUtils.isNotBlank(bankAccount.getBankCardNumber())
                && StringUtils.isNotBlank(bankAccount.getBankAccountName())) {
            biBankAccountService.insertBiBankAccount(bankAccount);
            return AjaxResult.success("添加成功");
        }else{
            return AjaxResult.error("必填参数不可为空");
        }
    }

    //立即提现
    @PostMapping("/shop/cashApply/add")
    public AjaxResult addCashApply(@RequestBody BiCashApply cashApply){
        try{
            return cashApplyService.insertBiCashApply(cashApply);
        }catch (Exception e){
            return AjaxResult.error("失败，请联系客服，错误："+e.getMessage());
        }

    }

    //提现申请列表查询
    @GetMapping("/shop/cashApply/list")
    public AjaxResult listCashApply(BiCashApply cashApply){
        if(StringUtils.isNotBlank(cashApply.getOpenid())) {
            return AjaxResult.success(cashApplyService.selectBiCashApplyList(cashApply));
        }else{
            return AjaxResult.success(new ArrayList<>());
        }
    }

    //账户明细查询-佣金明细
    @GetMapping("/shop/commission/list")
    public AjaxResult listCommission(BiCommission commission){
        if(StringUtils.isNotBlank(commission.getOpenid())) {
            return AjaxResult.success(commissionService.selectBiCommissionList(commission));
        }else{
            return AjaxResult.success(new ArrayList<>());
        }
    }

    //下级分店查询
    @GetMapping("/shop/child/list")
    public AjaxResult listChildShop(BiShop shop){
        if(StringUtils.isNotBlank(shop.getRecommendShopId())) {
            return AjaxResult.success(biShopService.selectBiShopList(shop));
        }else{
            return AjaxResult.success(new ArrayList<>());
        }
    }

    //添加学校
    @PostMapping("/shop/school/add")
    public AjaxResult addSchool(@RequestBody BiSchool school){
        if(StringUtils.isNotBlank(school.getSchoolName()) && StringUtils.isNotBlank(school.getOpenid())){
            school.setStatus(DataStatusEnum.WAIT_PASS.getStatus());
            biSchoolService.insertBiSchool(school);
            return AjaxResult.success("添加成功");
        }else{
            return AjaxResult.error("必填信息不可为空");
        }
    }

    //查询用户添加的学校列表
    @GetMapping("/shop/school/listByOpenid")
    public AjaxResult listByOpenid(BiSchool school){
        return success(biSchoolService.selectBiSchoolList(school));
    }

    //查询相似学校
    @GetMapping("/shop/school/getSimilar")
    public AjaxResult getSimilarSchool(BiSchool school){
        if(StringUtils.isNotBlank(school.getSchoolName())) {
            school.setStatus(DataStatusEnum.USABLE.getStatus());
            return success(biSchoolService.selectBiSchoolList(school));
        }else{
            return success(new ArrayList<>());
        }
    }

    //测试纸条抽取
    //@GetMapping("/test/cq")
    public AjaxResult testcq(){
        List<Long> list = biPaperService.extractPaper("123456", new Long(2), new Long(1), null);
        return AjaxResult.success(list);
    }
}
